const mysql = require('../server/node_modules/mysql2/promise');
const fs = require('fs').promises;
const path = require('path');

async function initializeDatabase() {
    let connection;

    try {
        // 创建数据库连接（使用硬编码配置）
        connection = await mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: '159680',
            database: 'juequ_zero_db'
        });

        console.log('数据库连接成功');

        // 读取SQL文件
        const sqlFile = path.join(__dirname, '../server/database/init.sql');
        const sql = await fs.readFile(sqlFile, 'utf8');

        // 执行SQL语句
        const statements = sql.split(';').filter(stmt => stmt.trim());
        for (const statement of statements) {
            if (statement.trim()) {
                try {
                    await connection.query(statement);
                    console.log('执行SQL语句成功:', statement.trim().substring(0, 50) + '...');
                } catch (error) {
                    // 如果是索引已存在的错误，则忽略
                    if (error.code === 'ER_DUP_KEYNAME') {
                        console.log('索引已存在，跳过创建:', error.sqlMessage);
                        continue;
                    }
                    // 如果是表已存在的错误，则忽略
                    if (error.code === 'ER_TABLE_EXISTS_ERROR') {
                        console.log('表已存在，跳过创建:', error.sqlMessage);
                        continue;
                    }
                    throw error;
                }
            }
        }

        console.log('数据库初始化完成');
    } catch (error) {
        console.error('数据库初始化失败:', error);
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

initializeDatabase();